package tech.jdbc.demo;

import tech.jdbc.util.JdbcUtil;

import java.sql.*;
import java.util.Scanner;

/**
 * Create with Intellij IDEA
 *
 * @Author Q
 * @date 2021/11/25/14:24
 */
public class MySqlClient {
    public static void main(String[] args) {
        client();
    }

    public static void client(){
        //定义一个StringBuilder对象,来拼接输入的sql语句
        StringBuilder builder = new StringBuilder();

        Scanner sc = new Scanner(System.in);
        System.out.print("mysql> ");
        while(true){
            String sql = sc.nextLine();//从键盘获取字符串
            builder.append(sql+" ");
            if(sql.endsWith(";")){
                //builder已经拼接好了一条完整的sql语句.

                //处理一下分号
                //StringBuilder是可以改变的字符串
                builder.deleteCharAt(builder.length()-2);
                //System.out.println(builder);
                //处理一下最后的空格
                //System.out.println(builder.toString().trim());

                execute(builder.toString().trim());

                //清空builder
                builder.delete(0,builder.capacity());
                System.out.print("mysql> ");
            }else{
                System.out.print("    -> ");
            }
        }
    }

    private static void execute(String sql) {
        Connection conn = null;
        Statement st = null;

        ResultSet rs = null;

        try {
            conn = JdbcUtil.getConnection();

            st = conn.createStatement();

            //有可能sql - DML
            //sql - DQL
            boolean flag = st.execute(sql);
            if(flag){
                //执行的是dql
                //System.out.println("query");
                //获取结果集的元数据对象
                rs = st.getResultSet();

                ResultSetMetaData rsmd = rs.getMetaData();
                //获取查询的列的个数
                int colsCount = rsmd.getColumnCount();

                //打印标题行
                for (int i = 1; i <=colsCount; i++) {
                    //System.out.print(rsmd.getColumnLabel(i)+"\t");
                    System.out.printf("%s\t\t",rsmd.getColumnLabel(i));
                }
                System.out.println();

                while(rs.next()){
                    //打印具体的内容
                    for (int i = 1; i <= colsCount; i++) {
                        System.out.printf("%s\t\t",rs.getObject(i));
                    }
                    System.out.println();
                }
            }else{
                //执行的是dml操作
                //System.out.println("update insert delete...");
                int count = st.getUpdateCount();
                System.out.println("Query OK, "+count+" row affected (0.00 sec)");
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(conn,st);
        }
    }
}
